﻿using Autofac;
using Common.Framework.Core.AutoMapper;
using Common.Framework.Core.Extension;
using Common.Framework.Core.Foundation;
using Common.Framework.Core.Middleware;
using Common.Framework.Core.SqlSugar;
using Microsoft.Extensions.Caching.Memory;
using SqlSugar;
using System.Collections.Generic;
using System.Linq;

namespace Common.Framework.Core.AutoFac
{
    /// <summary>
    /// 命名空间为AutoFac, 是为了和 Autofac区分
    /// </summary>
    public class AutofacLoadConfiguration : Module
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="builder"></param>
        protected override void Load(ContainerBuilder builder)
        {
            var assemblyArray = AssemblyFoundation.GetAllProjectAssemblies();

            #region 注入Service层
            builder.RegisterAssemblyTypes(assemblyArray) // find all types in the assembly
                    .Where(t => t.Name.EndsWith("Service")) // filter the types
                    .AsImplementedInterfaces().InstancePerLifetimeScope();  // register the service with all its public interfaces                   
            #endregion

            #region 注入Repository层            
            builder.RegisterAssemblyTypes(assemblyArray) // find all types in the assembly
                    .Where(t => t.Name.EndsWith("Repository")) // filter the types
                    .AsImplementedInterfaces().InstancePerLifetimeScope();  // register the service with all its public interfaces                   
            #endregion

            #region 注入AutoMapper
            AutoMapperConfiguration.AutoRegisterAutoMapper(builder, assemblyArray);
            #endregion

            #region 注入SqlSugar
            SqlSugarConfigure.AutoRegisterSqlSugar(builder);
            #endregion


            #region 自定义的中间件需要单独注入
            builder.RegisterType<AuthenticationCustomMiddleware>().AsSelf().InstancePerLifetimeScope();//InstancePerDependency();
            #endregion

            //内存级缓存可以直接使用.不需要单独注入.
            //如果以后需要用到redis,这里需要调整
            //属性注入本地缓存
            //builder.RegisterType<IMemoryCache>().InstancePerLifetimeScope();
            //builder.RegisterAssemblyTypes(assemblyArray).Where(s => s.Name == "IMemoryCache").PropertiesAutowired().AsImplementedInterfaces().InstancePerLifetimeScope();
        }

    }
}
